package controllers;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import auxilary.Links;

import database.StyleHandler;
import entities.User;

public class UploadController extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File tmpDir;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String path = getServletContext().getAttribute(
				"javax.servlet.context.tempdir").toString();
		tmpDir = new File(path);
		if (!tmpDir.isDirectory()) {
			throw new ServletException(path + " is not a directory");
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		if ((user == null) || (!user.isAdmin())) {
			request.getRequestDispatcher(
					"/errors/401.jsp").forward(
					request, response);
			return;
		}
		System.out.println("Uploading file...");
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */

		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);
		ServletFileUpload servletFileUpload = new ServletFileUpload(
				fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List<?> items = servletFileUpload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				// check there has been something uploaded and that it is of xsl type
				if ((!(item.isFormField()))
						&& (item.getName().endsWith(".xsl"))) {
					
					// check it doesnt crash with one of the basic styles
					if ((item.getName().equals("Box.Style.xsl"))
							|| (item.getName().equals("Table.Style.xsl"))) {
						request.getRequestDispatcher(
								"/errors/fileNameAlreadyExists.jsp").forward(
								request, response);
						return;
					}
					// Handle Uploaded files.
					InputStream is = item.getInputStream();
					StyleHandler sh = new StyleHandler();
					try {
						sh.addStyle(
								is,
								item.getName().substring(0,
										item.getName().length() - 4),
								item.getSize());
					} catch (Exception e) {
						request.getRequestDispatcher(
								"/errors/fileNameAlreadyExists.jsp").forward(
								request, response);
						return;
					}
					try {
						is.close();
					} catch (Exception e) {
					}
				} else {
					request.getRequestDispatcher("/errors/failedToUpload.jsp")
							.forward(request, response);
					return;
				}
			}
		} catch (Exception ex) {
			request.getRequestDispatcher("/WEB-INF/failedToUpload.jsp")
					.forward(request, response);
			return;
		}
		response.sendRedirect(response.encodeRedirectURL(Links.PROJECT_BASE
				+ "Users/schedule"));
	}

}
